package com.zhukunri.sp02.controller;

import com.zhukunri.sp01.domain.Item;
import com.zhukunri.sp01.service.ItemService;
import com.zhukunri.sp01.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {

    @Autowired
    private ItemService itemService;

    /*
    JsonResult：封装返回给客户端的工具
        - code:状态码
        - msg:提示消息
        - data:数据
     */

    //获取订单的商品列表
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws InterruptedException {
        //根据订单的id获取商品数据
        List<Item> items = itemService.getItems(orderId);
        //封装成json数据
        JsonResult result = JsonResult.ok().data(items);

        //随机的延迟代码
        if (Math.random() < 0.9){//90%的概率执行延迟
            //随机延迟时长
            int nextInt = new Random().nextInt(5000);
            log.info("随机延迟："+nextInt);
            Thread.sleep(nextInt);
        }


        //返回
        return result;
    }

    //减少商品库存
    @PostMapping("/descreaseNumber")
    public JsonResult<?> descreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        JsonResult result = JsonResult.ok().msg("减少商品库存成功");
        return result;
    }
}
